//
//  QXHomeTableVC.swift
//  QXWeibo
//
//  Created by QinXin on 15/6/23.
//  Copyright © 2015年 labi3285_Lab. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage

class QXHomeTableVC: QXBaseTableVC, QXStatusCellDelegate {
    
    var statusesData: [QXStatus]? {
        didSet {
            tableView.reloadData()
        }
    }
    
    // 上拉刷新标记
    private var upwardFlag = false
    func loadData() {
        
        refreshControl?.beginRefreshing()
        
        var sinceId = statusesData?.first?.id ?? 0
        var maxId = 0

        if upwardFlag {
            sinceId = 0
            maxId = (statusesData?.last?.id)!
        }
        
        QXStatus.loadStatus(sinceId, max_id: maxId) { (statuses, error) -> () in
                        
            self.refreshControl?.endRefreshing()
            
            if error != nil {
                SVProgressHUD.showInfoWithStatus("访问失败，请检查网络！")
            }
            if statuses == nil {
                return
            }
            if sinceId > 0 {
                self.statusesData = statuses! + self.statusesData!
            } else if maxId > 0 {
                self.statusesData = self.statusesData! + statuses!
                self.upwardFlag = false
            } else {
                self.statusesData = statuses
            }
            
        }
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        visitView?.setupViewInfo("visitordiscover_feed_image_house", message: "关注一些人，看看有什么惊喜", isHome: true)
        
        if !isLogon {
            return
        }
        
        setupNavgationBar()
        
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        tableView.allowsSelection = false
        tableView.registerClass(QXStatusNormalCell.self, forCellReuseIdentifier: "QXStatusNormalCell")
        tableView.registerClass(QXStatusForwardCell.self, forCellReuseIdentifier: "QXStatusForwardCell")
        
        refreshControl = QXRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        loadData()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        visitView?.startAnimation()
    }
    
    private func setupNavgationBar() {
        if sharedAccount == nil {
            return
        }
        
        let leftBtn = UIButton()
        
        leftBtn.bounds = CGRectMake(0, 0, 30, 30)
        
        navigationItem.leftBarButtonItem = QXBarButtonItem(imageName: "navigationbar_friendsearch", highlightedImageName: nil, clicked: {
            self.presentViewController(QXQRCodeMyselfVC.create(), animated: true, completion: nil)
        })
        
        navigationItem.rightBarButtonItem = QXBarButtonItem(imageName: "navigationbar_pop", highlightedImageName: nil, clicked: {
            self.presentViewController(QXQRCodeVC.create(), animated: true, completion: nil)
        })
        
        let titleBtn = QXHomeTitleBtn.create(sharedAccount!.name! + " ")
        titleBtn.addTarget(self, action: "showCenterPopMenu", forControlEvents: UIControlEvents.TouchUpInside)

        navigationItem.titleView = titleBtn

    }
    
    func showCenterPopMenu() {
        presentViewController(QXPopoverCenterVC.create(), animated: true, completion: nil)
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let status = statusesData![indexPath.row]
        
        var id = "QXStatusNormalCell"
        if status.retweeted_status != nil {
            id = "QXStatusForwardCell"
        }
        
        let cell = tableView.dequeueReusableCellWithIdentifier(id, forIndexPath: indexPath) as! QXStatusCell
        cell.status = statusesData![indexPath.row]
        
        if indexPath.row == (statusesData?.count)! - 1 {
            
            upwardFlag = true
            loadData()
        }
        
        cell.picDelegate = self
        
        return cell
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusesData?.count ?? 0
    }
    
    lazy var rowHeightDic = [Int: CGFloat]()
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let status = statusesData![indexPath.row]
        if rowHeightDic[status.id] != nil {
            return rowHeightDic[status.id]!
        }
        
        var h: CGFloat?
        
        // 这里需要创建新的cell（新版本的bug）
        if status.retweeted_status != nil {
            let cell = QXStatusForwardCell()
            h = cell.rowHeight(status)
            rowHeightDic[status.id] = h
        } else {
            let cell = QXStatusNormalCell()
            h = cell.rowHeight(status)
            rowHeightDic[status.id] = h
        }

        return h!
    }
    
    /// 代理方法
    func statusCellDidSelectPic(cell: QXStatusCell, idx: Int) {
        
        if cell.status?.allLargeImageURLs == nil {
            return
        }
        
        // 缓存当前的statusCell
        currentStatusCell = cell
        
        // 为过度图片框添加图片
        presentedImageView.sd_setImageWithURL(cell.status?.allLargeImageURLs![idx])
        
        // 设置原始frame为当前缩略图的绝对frame
        presentedImageView.frame = getOriginImageFrame(idx)
        // 这个样式为了保持过度效果的平滑
        presentedImageView.contentMode = UIViewContentMode.ScaleAspectFill

        // 取得缓存的缩略图（为了计算放大后的尺寸）
        let urlStr = cell.status!.allLargeImageURLs![idx].absoluteString
        
        currentImage = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlStr)
        
        if currentImage == nil {
            return
        }
        
        // 计算放大后的图片frame
        var w: CGFloat
        var h: CGFloat
        var x: CGFloat
        var y: CGFloat
        
        let winSize = UIScreen.mainScreen().bounds.size
        let imgSize = currentImage!.size
        
        let k = winSize.width / winSize.height
        let k1 = imgSize.width / imgSize.height
        if k > k1 {
            w = winSize.width
            h = w / k1
            x = 0
            y = 0
        } else {
            w = winSize.width
            h = w / k1
            x = 0
            y = (winSize.height - h) * 0.5
        }
        presentedFrame = CGRectMake(x, y, w, h)
        
        // 转场
        let vc = QXPhotoViewerVC(urls: (cell.status?.allLargeImageURLs)!, idx: idx)

        selectedStatusCell = cell
        vc.transitioningDelegate = self
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(vc, animated: true, completion: nil)
    }
    
    
    // 用于图片的转场
    var isPresented = false
    private lazy var presentedImageView = UIImageView()
    private var originFrame = CGRectZero
    private var presentedFrame = CGRectZero
    private var currentImage: UIImage?
    private var currentStatusCell: QXStatusCell?
    private var selectedStatusCell: QXStatusCell?
    
    func getOriginImageFrame(idx: Int) -> CGRect {
        // 取得点击的图片cell
        let picCell = currentStatusCell!.picView.cellForItemAtIndexPath(NSIndexPath(forItem: idx, inSection: 0)) as! QXWebImageCollectionViewCell
        // 设置原始frame为当前缩略图的绝对frame
        return picCell.superview!.convertRect(picCell.frame, toCoordinateSpace: view.window!)
    }
    
}


extension QXHomeTableVC: UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
    
    // 返回提供转场 Modal 动画的对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresented = true
        return self
    }
    
    // 返回提供转场 Dismiss 动画的对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresented = false
        return self
    }
    
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
    
    // 一旦实现，需要程序员提供动画
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        // 1. 获取目标视图
        let viewKey = isPresented ? UITransitionContextToViewKey : UITransitionContextFromViewKey
        let vcKey = isPresented ? UITransitionContextToViewControllerKey : UITransitionContextFromViewControllerKey
        let targetView = transitionContext.viewForKey(viewKey)
        let targetVc = transitionContext.viewControllerForKey(vcKey)
        
        if targetView == nil {
            return
        }
        
        if isPresented {
            // 2. 添加 toView
            transitionContext.containerView()?.addSubview(targetView!)
            targetView!.alpha = 0
            // 2.1 添加临时的图片视图
            transitionContext.containerView()?.addSubview(presentedImageView)
            
            // 3. 动画
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                
                self.presentedImageView.frame = self.presentedFrame
                
                }, completion: { (_) -> Void in
                    // 删除临时图片视图
                    self.presentedImageView.removeFromSuperview()
                    targetView!.alpha = 1
                    self.presentedImageView.removeFromSuperview()
                    // *** 告诉动画完成
                    transitionContext.completeTransition(true)
            })
        } else {
            
            let imageFrame = (targetVc as! QXPhotoViewerVC).getCurrentImageViewAbsoluteFrame()
            let imageView = (targetVc as! QXPhotoViewerVC).getCurrentImageView()
            let idx = (targetVc as! QXPhotoViewerVC).getCurrentImageIdx()
            let toFrame = getOriginImageFrame(idx)
            
            // 创建一个用于转场的图片
            imageView.frame = imageFrame
            transitionContext.containerView()?.addSubview(imageView)
            
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                
                targetView?.removeFromSuperview()
                imageView.frame = toFrame
                
                }, completion: { (_) -> Void in
                    transitionContext.completeTransition(true)
            })
            
        }
    }
}
